package com.kfm.ajax.service.impl;

import com.kfm.ajax.mapper.RoleModelMapper;
import com.kfm.ajax.mapper.UserModelMapper;
import com.kfm.ajax.model.MenuModel;
import com.kfm.ajax.model.RoleModel;
import com.kfm.ajax.model.UserModel;
import com.kfm.ajax.model.UserModelDTO;
import com.kfm.ajax.service.MenuService;
import com.kfm.ajax.service.UserModelService;
import com.kfm.ajax.service.exception.ServiceException;
import com.kfm.ajax.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserModelServiceImpl implements UserModelService {

    @Autowired
    private UserModelMapper userModelMapper;
    @Autowired
    private RoleModelMapper roleModelMapper;

    @Autowired
    private MenuService menuService;


    @Override
    public UserModel login(UserModel userModel) throws ServiceException {
        if (userModel == null || userModel.getUsername() == null || userModel.getPassword() == null){
            throw new ServiceException("用户名或密码不能为空");
        }
        // 密码加密
         userModel.setPassword(MD5Util.encodePassword(userModel.getPassword(), userModel.getUsername()));
        List<UserModel> userModels = userModelMapper.selectAll(userModel);
        if (userModels.size() == 1){
            UserModel model = userModels.get(0);
            // 判断用户状态
            if (model.getState() == 0){
                throw new ServiceException("用户已被禁用");
            }
            // TODO 可以异步处理 SpringBoot @Async
            // 查询角色信息
            List<RoleModel> roleModels = roleModelMapper.selectByUserId(model.getId());
            // 查询菜单信息
            // 获取用户角色ID 数组
            Integer[] roleIds = new Integer[roleModels.size()];
            for (int i = 0; i < roleModels.size(); i++) {
                roleIds[i] = roleModels.get(i).getId();
            }
            List<MenuModel> menuModels = menuService.selectByRoleId(roleIds);
            return new UserModelDTO(model, roleModels, menuModels);
        } else {
            return null;
        }
    }
}
